package cn.ahaoweb.drule.core.compile;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Name: 效验结果
 * @Description:
 * @Author: wangzhonghao
 * @Date: 2025/2/18 11:06
 */
@Setter
@Getter
public class ValidateResult implements Serializable {

    public static final int SUCCESS = 0;
    public static final int ERROR = 500;

    /**
     * 返回码
     */
    private Integer code;

    /**
     * 消息列表
     */
    private List<Message> messages = new ArrayList<>();

    public ValidateResult() {}

    /**
     * 构造器
     */
    public ValidateResult(Integer code) {
        this.code = code;
    }

    public static ValidateResult success() {
        return new ValidateResult(SUCCESS);
    }

    public static ValidateResult success(String msg) {
        return new ValidateResult(SUCCESS);
    }

    public static ValidateResult error(Integer code) {
        return new ValidateResult(code);
    }

    public boolean isSuccess(){
        return Objects.equals(SUCCESS,this.code);
    }

    public void addMessage(String title,String text){
        addMessage(title,text,null);
    }

    /**
     * 消息内容
     * @param title
     * @param text
     * @param seq 同一个消息中内容分隔符
     */
    public void addMessage(String title,String text,String seq){
        Message message = null;
        for (Message msg : messages) {
            if (Objects.equals(msg.getTitle(),title)){
                message = msg;
                break;
            }
        }
        if (message == null){
            message = new Message(title, new ArrayList<>());
            messages.add(message);
        }
        if (seq != null){
            message.seq = seq;
        }
        message.add(text);
    }

    public String print(){
        if (messages != null){
            StringBuilder sb = new StringBuilder();
            for (Message message : messages) {
                sb.append(message.getText()).append("\n");
            }
            return sb.toString();
        }
        return "";
    }

    @Data
    public static class Message{

        private String title;

        // 分隔符
        private String seq = ",";

        private List<String> content;

        public Message(String title, List<String> content) {
            this.title = title;
            this.content = content;
        }

        public void add(String con){
            content.add(con);
        }

        public String getText() {
            StringBuilder stringBuilder = new StringBuilder()
                    .append(title)
                    .append(": ");
            for (int i = 0; i < content.size(); i++) {
                String s = content.get(i);
                if (i != 0){
                    stringBuilder.append(seq);
                }
                stringBuilder.append(s);
            }
            return stringBuilder.toString();
        }

    }
}
